{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "1605a770-a989-4029-bf95-fab3753fe8a3",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7afda45b-2fda-4879-93b7-0e9a6698e3f3",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "# 1. 创建一个tensor的不同方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "21797f28-efc5-4196-ad51-dbc36e89fa7a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor([1, 2, 3]), tensor([[1, 2, 3]]), tensor([[[1, 2, 3]]]))"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 创建三个不用维度的tensor\n",
    "# 直接手动输入\n",
    "one_dim = torch.tensor([1,2,3]) # 一维时为向量\n",
    "two_dim = torch.tensor([[1,2,3]]) # 二维时为矩阵\n",
    "three_dim = torch.tensor([[[1,2,3]]]) # 三维及以上统称为tensor\n",
    "one_dim, two_dim, three_dim"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c8015c34-c122-4e4b-8aad-fe080765becb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor([[[0.1170, 0.3186, 0.2398]]]),\n",
       " tensor([[[1., 1., 1.]]]),\n",
       " tensor([[[0., 0., 0.]]]))"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 依照给定shape生成\n",
    "rand_tensor = torch.rand(1,1,3) # 数值为[0,1)的均匀分布\n",
    "ones_tensor = torch.ones(1,1,3)\n",
    "zeros_tensor = torch.zeros(1,1,3)\n",
    "\n",
    "rand_tensor, ones_tensor, zeros_tensor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "a497b893-ed04-4963-9871-ceb49712b22f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor([[[0.9788, 0.6083, 0.1664]]]), tensor([[[1., 1., 1.]]]))"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 依照别的tensor生成\n",
    "three_dim = torch.tensor([[[1.,2.,3.]]])\n",
    "\n",
    "rand_tensor = torch.rand_like(three_dim)\n",
    "ones_tensor = torch.ones_like(three_dim)\n",
    "\n",
    "rand_tensor, ones_tensor"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a967c889-0702-4d59-881a-594e52b4ecc1",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "# 2. 查看创建好的tensor的相关信息"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "cdcca4d6-d0a6-4196-a735-6ddf8242ea0c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([0.7850, 0.4236, 0.2115])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Long型的运算\n",
    "one_dim = torch.tensor([1.,2.,3.])\n",
    "x = torch.rand_like(one_dim)\n",
    "x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "8f6678f4-577f-4770-879a-8b72fa330132",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cuda:0\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "tensor([[1.1296, 0.4521],\n",
       "        [1.0114, 0.3211]], device='cuda:0')"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 位于CPU和GPU的两tensor做运算\n",
    "device = 'cuda:0' if torch.cuda.is_available() else 'cpu'\n",
    "print(device)\n",
    "\n",
    "x = torch.rand(2,2,device=device)\n",
    "y = torch.rand(2,2)\n",
    "x + y.to(device)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "48ad6ba6-3e54-486a-8b81-eafbb8684747",
   "metadata": {},
   "outputs": [
    {
     "ename": "RuntimeError",
     "evalue": "The size of tensor a (2) must match the size of tensor b (3) at non-singleton dimension 1",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mRuntimeError\u001b[0m                              Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[10], line 4\u001b[0m\n\u001b[0;32m      2\u001b[0m x \u001b[38;5;241m=\u001b[39m torch\u001b[38;5;241m.\u001b[39mrand(\u001b[38;5;241m2\u001b[39m,\u001b[38;5;241m2\u001b[39m)\n\u001b[0;32m      3\u001b[0m y \u001b[38;5;241m=\u001b[39m torch\u001b[38;5;241m.\u001b[39mrand(\u001b[38;5;241m3\u001b[39m,\u001b[38;5;241m3\u001b[39m)\n\u001b[1;32m----> 4\u001b[0m \u001b[43mx\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m+\u001b[39;49m\u001b[43m \u001b[49m\u001b[43my\u001b[49m\n",
      "\u001b[1;31mRuntimeError\u001b[0m: The size of tensor a (2) must match the size of tensor b (3) at non-singleton dimension 1"
     ]
    }
   ],
   "source": [
    "# 两个shape不同的tensor做运算\n",
    "x = torch.rand(2,2)\n",
    "y = torch.rand(3,3)\n",
    "x + y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "a8a5f175-5f63-45cd-8292-7dede774d6e5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cuda:0\n",
      "torch.float32\n",
      "cuda:0\n",
      "torch.Size([2, 2])\n"
     ]
    }
   ],
   "source": [
    "# tensor重要的属性：dtype, device, shape\n",
    "device = 'cuda:0' if torch.cuda.is_available() else 'cpu'\n",
    "print(device)\n",
    "\n",
    "x = torch.rand(2,2,device=device)\n",
    "print(x.dtype)\n",
    "print(x.device)\n",
    "print(x.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62a647fe-ada2-4fc7-a5c9-b846597474ff",
   "metadata": {},
   "source": [
    "# 3. tensor的运算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "b9170e4e-be28-4e83-986d-1feb5cc28b5f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[1., 0., 1., 1.],\n",
      "        [1., 0., 1., 1.],\n",
      "        [1., 0., 1., 1.],\n",
      "        [1., 0., 1., 1.]])\n"
     ]
    }
   ],
   "source": [
    "# indexing（索引）与slicing（切片）\n",
    "tensor = torch.ones(4, 4)\n",
    "tensor[:,1] = 0\n",
    "print(tensor)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "0685e06c-1cf9-4e3b-9a43-db8033e8b917",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[1., 1., 1., 1., 1., 1., 1., 1., 1.],\n",
       "        [1., 1., 1., 1., 1., 1., 1., 1., 1.]])"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 堆叠tensor\n",
    "tensor = torch.ones(2, 3)\n",
    "tensor_cat = torch.cat([tensor, tensor, tensor], dim=1)\n",
    "tensor_cat"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "3e013442-089b-42ec-a68b-2e22d368652f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[2., 2., 2.],\n",
       "        [2., 2., 2.],\n",
       "        [2., 2., 2.]])"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 两个tensor加减（维度相同）\n",
    "x1 = torch.ones(3,3)\n",
    "x2 = torch.ones(3,3)\n",
    "x1 + x2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "86ac8445-d319-4b87-8481-f1b23455f5bc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[1.1656, 1.2699, 1.7637],\n",
       "        [1.4880, 1.9893, 1.6926],\n",
       "        [1.9923, 1.9103, 1.5053]])"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 两个tensor加减（维度不同，属于特殊情况）\n",
    "x1 = torch.ones(1,3)\n",
    "x2 = torch.rand(3,3)\n",
    "x1 + x2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "9a641cec-2cf9-4ddf-99fb-e9c716f9b6dd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[0.0950, 0.1850, 0.7992],\n",
      "        [0.4596, 0.4764, 0.7313]])\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "tensor([[0.0950, 0.1850, 0.7992],\n",
       "        [0.4596, 0.4764, 0.7313]])"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 两个tensor相乘（element-wise）\n",
    "x1 = torch.ones(2, 3)\n",
    "x2 = torch.rand(2, 3)\n",
    "\n",
    "print(x2)\n",
    "x1 * x2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "8e9f9dc1-51ef-4efd-a93f-b6f8e154b3e3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "x2:  tensor([[0.6370, 0.9080, 0.1730],\n",
      "        [0.6288, 0.2830, 0.5226]]) \n",
      "\n",
      "tensor([[1.2658, 1.1911, 0.6957],\n",
      "        [1.2658, 1.1911, 0.6957],\n",
      "        [1.2658, 1.1911, 0.6957]])\n",
      "tensor([[1.2658, 1.1911, 0.6957],\n",
      "        [1.2658, 1.1911, 0.6957],\n",
      "        [1.2658, 1.1911, 0.6957]])\n"
     ]
    }
   ],
   "source": [
    "# 两个tensor相乘（matrix multiplication）\n",
    "x1 = torch.ones(2, 3)\n",
    "x2 = torch.rand(2, 3)\n",
    "\n",
    "print('x2: ', x2, '\\n')\n",
    "print(x1.t().matmul(x2))\n",
    "print(x1.t() @ x2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8078a23f-959d-45d1-a36b-4b53760af65e",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
